package com.sita.friend.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.services.core.LatLonPoint;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.sita.bike.R;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.BitmapUtils;
import com.sita.friend.event.CalculateDriveRouteEvent;
import com.sita.friend.event.SendDestinationEvent;
import com.sita.tboard.ActivityBase;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 创建时间：11/11/15 17:32
 * 项目名称：newNaviDemo
 *
 * @author lingxiang.wang
 * @email lingxiang.wang@alibaba-inc.com
 * 类说明：
 */

public class RoutePlanningActivity extends ActivityBase implements AMap.OnMapScreenShotListener {
    private static final int TAKE_LOCATION = 0x000002;
    private EMMessage mEMMessage;
    private String locationlab;
    private LatLonPoint latLonPoint;
    // 地图和导航资源
    private TextureMapView mMapView;
    private AMap mAMap;
    private AMapNavi aMapNavi;
    private Marker destionationMarker;
    private MarkerOptions destionationMarkerOption;
    private Button cancelSendDestination, sendDestination;
    private ImageView routePlan, cancelRoutePlan;
    private RelativeLayout titleBar, routePlanBar;
    private TextView lab;
    private PopupWindow routePlanPop = null;
    private LinearLayout layoutRoutePlanPopup;
    private View parentView;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parentView = getLayoutInflater().inflate(R.layout.activity_route_planning, null);
        setContentView(parentView);
        mEMMessage = getIntent().getParcelableExtra("DISTINATION_MESSAGE");
        locationlab = getIntent().getStringExtra("myLocation");
        latLonPoint = getIntent().getParcelableExtra("latLonPoint");
        initView(savedInstanceState);
        addDestination();
    }

    // 初始化View
    private void initView(Bundle savedInstanceState) {
        titleBar = (RelativeLayout) findViewById(R.id.layout_title_bar);
        routePlanBar = (RelativeLayout) findViewById(R.id.layout_route_plan_bar);
        lab = (TextView) findViewById(R.id.txt_lab);
        cancelSendDestination = (Button) findViewById(R.id.btn_cancel_send);
        cancelSendDestination.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cancelRoutePlan = (ImageView) findViewById(R.id.cancel_route_plan);
        cancelRoutePlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        sendDestination = (Button) findViewById(R.id.btn_send_distination);
        sendDestination.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMapScreenShot(v);
            }
        });

        routePlanPop = new PopupWindow(this);
        View routePlanView = getLayoutInflater().inflate(R.layout.popup_windows_route_plan, null);
        layoutRoutePlanPopup = (LinearLayout) routePlanView.findViewById(R.id.layout_route_plan_popup);

        routePlanPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        routePlanPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        routePlanPop.setBackgroundDrawable(new BitmapDrawable());
        routePlanPop.setFocusable(true);
        routePlanPop.setOutsideTouchable(true);
        routePlanPop.setContentView(routePlanView);

        RelativeLayout routePlanParent = (RelativeLayout) routePlanView.findViewById(R.id.route_plan_parent);
        Button selfRoutePlan = (Button) routePlanView.findViewById(R.id.btn_self_route_plan);
        Button toAmap = (Button) routePlanView.findViewById(R.id.btn_to_amap);
        Button toBaidu = (Button) routePlanView.findViewById(R.id.btn_to_baidu_map);
        Button routePlanCancel = (Button) routePlanView.findViewById(R.id.btn_route_plan_cancel);
        routePlanParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
            }
        });
        selfRoutePlan.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
                //点击规划路径，传给chatActivity终点的坐标
                EventBus.getDefault().post(new CalculateDriveRouteEvent(mEMMessage));
                finish();
            }
        });
        toAmap.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //测试跳转第三方
                if (isAvilible(getApplicationContext(), "com.autonavi.minimap")) {//传入指定应用包名
                    Intent intent = null;
                    try {
                        String poiname = null;
                        String lat = null;
                        String lon = null;
                        if (mEMMessage != null) {
                            try {
                                poiname = mEMMessage.getStringAttribute("locationlab");
                                lat = mEMMessage.getStringAttribute("poiLatitude");
                                lon = mEMMessage.getStringAttribute("poiLongitude");
                            } catch (EaseMobException e) {
                                e.printStackTrace();
                            }
                        }
                        intent = Intent.getIntent("androidamap://viewMap?sourceApplication=摩趣&poiname=" + poiname +
                                "&lat=" + lat +
                                "&lon=" + lon + "&dev=0");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();

            }
        });
        toBaidu.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (isAvilible(getApplicationContext(), "com.baidu.BaiduMap")) {//传入指定应用包名
                    Intent intent = null;
                    try {
                        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
                        String latLngStart = "latlng:" + location.getLatitude() + "," + location.getLongitude();
                        String latLngEnd = null;
                        if (mEMMessage != null) {
                            try {
                                latLngEnd = "latlng:" + mEMMessage.getStringAttribute("poiLatitude") + "," + mEMMessage.getStringAttribute("poiLongitude");
                            } catch (EaseMobException e) {
                                e.printStackTrace();
                            }
                        }
                        intent = Intent.getIntent("intent://map/direction?" +
                                "origin=" + latLngStart + "|name:起点&" +
                                "destination=" + latLngEnd + "|name:终点&" +
                                "&mode=driving&" + //导航方式
                                "&src=com.sita.bike#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    //market为路径，id为包名
                    //显示手机上所有的market商店
                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
            }
        });


        routePlanCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
            }
        });


        //点击按钮弹出pop,选择导航方式
        routePlan = (ImageView) findViewById(R.id.btn_route_plan);
        routePlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutRoutePlanPopup.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.activity_translate_in));
                routePlanPop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
            }
        });

        mMapView = (TextureMapView) findViewById(R.id.mapview);
        mMapView.onCreate(savedInstanceState);
        initMap();
    }

    protected void initMap() {
        if (mAMap == null) {
            mAMap = mMapView.getMap();
        }
        aMapNavi = AMapNavi.getInstance(this);
        aMapNavi.setEmulatorNaviSpeed(150);

    }

    private void addDestination() {
        if (latLonPoint != null) {
            LatLng latLng = new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
            addDestinationMarkerToMap(latLng);
            CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
            CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
            mAMap.moveCamera(update);
            sendDestination.setVisibility(View.VISIBLE);
        }

        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (mEMMessage != null) {
            try {
                latLng = new LatLng(Double.parseDouble(mEMMessage.getStringAttribute("poiLatitude")), Double.parseDouble(mEMMessage.getStringAttribute("poiLongitude")));
                addDestinationMarkerToMap(latLng);
                lab.setText(mEMMessage.getStringAttribute("locationlab"));
                titleBar.setVisibility(View.GONE);
                cancelRoutePlan.setVisibility(View.VISIBLE);
                routePlanBar.setVisibility(View.VISIBLE);
                CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
                CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
                mAMap.moveCamera(update);
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 在地图上添加目的地的marker
     */
    private void addDestinationMarkerToMap(LatLng latlng) {
        if (destionationMarkerOption == null) {
            destionationMarkerOption = new MarkerOptions();
            destionationMarkerOption.position(latlng);
            destionationMarkerOption.title("天津市").snippet("天津市");
            destionationMarkerOption.draggable(true);
            Bitmap redpin = BitmapFactory.decodeResource(getResources(), R.drawable.location_b);
            Bitmap redpin_zoom = BitmapUtils.zoomBitmap(redpin, 100, 100);
            destionationMarkerOption.icon(
                    BitmapDescriptorFactory.fromBitmap(redpin_zoom));
            // 将Marker设置为贴地显示，可以双指下拉看效果
            destionationMarkerOption.setFlat(true);
            destionationMarker = mAMap.addMarker(destionationMarkerOption);
        } else {
            destionationMarker.setPosition(latlng);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    /**
     * 对地图进行截屏
     */
    public void getMapScreenShot(View v) {
        //先将目的地移到地图中心
        LatLng latlng = new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
        CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        mAMap.moveCamera(update);
        // 设置截屏监听接口，截取地图可视区域
        mAMap.getMapScreenShot(this);
    }

    @Override
    public void onMapScreenShot(Bitmap bitmap) {
        Bitmap crop = ImageCrop(bitmap);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            // 保存在SD卡根目录下，图片为png格式。
            String path = Environment.getExternalStorageDirectory() + "/test_" + sdf.format(new Date()) + ".png";
            FileOutputStream fos = new FileOutputStream(path);
            boolean b = crop.compress(Bitmap.CompressFormat.PNG, 100, fos);
            try {
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (b) {
                Toast.makeText(this, "截屏成功", Toast.LENGTH_SHORT);
                EventBus.getDefault().post(new SendDestinationEvent("RoutePlanningActivity", latLonPoint, path, locationlab));
                this.finish();
            } else {
                Toast.makeText(this, "截屏失败", Toast.LENGTH_SHORT);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMapScreenShot(Bitmap bitmap, int i) {

    }

    /**
     * 裁切图片
     */
    public Bitmap ImageCrop(Bitmap bitmap) {
        int w = bitmap.getWidth(); // 得到图片的宽，高
        int h = bitmap.getHeight();
        int retX = w / 6;//基于原图，取正方形左上角x坐标
        int retY = h / 2 - w / 6;
        return Bitmap.createBitmap(bitmap, retX, retY, 2 * w / 3, w / 3, null, true);
    }

    /**
     * * 检查手机上是否安装了指定的软件
     * * @param context
     * * @param packageName：应用包名
     * * @return
     */
    private boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        List<String> mappackages = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }
}